#include "developarea.h"
#include "ui_developarea.h"
#include <QDebug>

DevelopArea::DevelopArea(HousingDBMS *p_dbms, HousingSettings *p_hs, QWidget *parent) :
    QWidget(parent),
    mp_dbms(p_dbms),
    mp_hs(p_hs),
    mp_current_tedit(NULL),
    ui(new Ui::DevelopArea)
{
    ui->setupUi(this);
    mp_dbtable = new FormTableViewer(mp_dbms,this);
    ui->layout_tableview->addWidget(mp_dbtable,0,0,0,0);

    hide();
}

DevelopArea::~DevelopArea()
{
    delete ui;
}

void DevelopArea::on_btn_form_street_dict_clicked()
{
    QFile txt_file;
    txt_file.setFileName(mp_hs->str_home_path +"/txt_db/lakinsk-streets-db.txt");
    if(!txt_file.open(QIODevice::ReadOnly))
    {
        qCritical()<<"Unable to open streets txt data";
        return ;
    }
    QTextStream txt_in(&txt_file);
    QString data_str, street_str;
    int street_type = 0xFF;
    QVariant qv_key, qv_data;
    QChar   qch;
    SLEE_HDB_REC qh_data;
    bool wait_street = true;
    while(!txt_in.atEnd())
    {
        txt_in>>qch;
        if((qch == '\t') || (qch == '\n') || (qch == '\r'))
        {
            if(data_str.size() < 2)
            {
                data_str.clear();
                continue;
            }
            if(wait_street)
            {
                street_str = data_str;
                data_str.clear();
                wait_street = false;
                continue;
            }
            else
            {
                if(data_str == RUSTR("ул")) street_type = ST_STRT;
                else if (data_str == RUSTR("пер")) street_type = ST_LANE;
                else if (data_str == RUSTR("проезд")) street_type = ST_PASS;
                else if (data_str == RUSTR("тер")) street_type = ST_TERR;
                wait_street = true;
                street_str = street_str.toUpper();
                qv_key = street_str;
                qv_data = street_type;
                qDebug()<<data_str<<street_str<<street_type;
                qh_data[0] = QVariant(street_str);
                qh_data[1] = QVariant(street_type);
                if(qrand()%100 > 70)
                    mp_dbms->db_put(LAKDB_STREETS,qh_data);
                data_str.clear();
                street_str.clear();
                continue;
            }
        }
        data_str.append(qch);
    }
    txt_file.close();
}

void DevelopArea::on_btn_form_families_dict_clicked()
{
//    QFile txt_file;
//    txt_file.setFileName(mp_hs->str_home_path +"/txt_db/families-db.txt");
//    if(!txt_file.open(QIODevice::ReadOnly))
//    {
//        qCritical()<<"Unable to open families txt data";
//        return ;
//    }
//    QTextStream txt_in(&txt_file);
//    QString fam_str;
//    QStringList fam_lst;
//    while(!txt_in.atEnd())
//    {
//        txt_in>>fam_str;
//        if(fam_str.size() < 2) continue;
//        fam_str = fam_str.toUpper();
//        if(fam_lst.contains(fam_str)) continue;
//        fam_lst.append(fam_str);
//    }
//    QVariant qv_key;
//    SLEE_HDB_REC qh_data;
//    qh_data[0] = 0;
//    foreach(QString str_, fam_lst)
//    {
//        qv_key = str_;
//        mp_dbms->db_put(LAKDB_FAMILIES_DICT,qh_data,qv_key);
//        qDebug()<<str_;
//    }
//    txt_file.close();
}

void DevelopArea::on_btn_form_names_dict_clicked()
{
//    QFile txt_file;
//    txt_file.setFileName(mp_hs->str_home_path +"/txt_db/names-db.txt");
//    if(!txt_file.open(QIODevice::ReadOnly))
//    {
//        qCritical()<<"Unable to open names txt data";
//        return ;
//    }
//    QTextStream txt_in(&txt_file);
//    QString name_str;
//    QStringList name_lst;
//    while(!txt_in.atEnd())
//    {
//        txt_in>>name_str;
//        if(name_str.size() < 2) continue;
//        name_str = name_str.toUpper();
//        if(name_lst.contains(name_str)) continue;
//        name_lst.append(name_str);
//    }
//    QVariant qv_key;
//    SLEE_HDB_REC qh_data;
//    qh_data[0] = 0;
//    foreach(QString str_, name_lst)
//    {
//        qv_key = str_;
//        mp_dbms->db_put(LAKDB_NAMES_DICT,qh_data,qv_key);
//        qDebug()<<str_;
//    }

//    txt_file.close();
}

void DevelopArea::on_btnClose_clicked()
{
    hide();
}

void DevelopArea::on_combo_tables_currentIndexChanged(int index)
{
    if(mp_current_tedit != NULL)
    {
        ui->layout_tableedit->removeWidget(mp_current_tedit);
        mp_current_tedit->hide();
    }
    switch(index)
    {
        case LAKDB_STREETS:
            break;
       case LAKDB_HOUSES:
            break;
    case LAKDB_APARTMENTS:
            break;
//    case LAKDB_PERSONS:
//            ui->layout_tableedit->addWidget(mp_persons_editor,0,0,0,0);
//            mp_persons_editor->show();
//            mp_current_tedit = mp_persons_editor;
            break;//do not forget set the break at last case
    case LAKDB_TENANTS:
            break;
    default:
        mp_current_tedit = NULL;
    }
}

void DevelopArea::data_selected(QVariant qv_pkey, QHash<int, QVariant> qh_data)
{
    qDebug()<<"selected prim key:"<<qv_pkey;
    qDebug()<<"selected data:"<<qh_data;
}


void DevelopArea::on_btn_form_houses_clicked()
{
   QVariantList qv_pkeys_lst;
   QVariant qv_re_key;
   double sqrs[4] = {20.0, 40.0, 16.0, 53.0};
   qv_pkeys_lst = mp_dbms->get_db(LAKDB_STREETS)->findDataRange(-1);
   int hn;
   SLEE_HDB_REC qh_data;
   for(int i = 0; i<qv_pkeys_lst.size(); i++)
   {
       hn = rand()%4+1;
       qDebug()<<"street it"<<i<<" hn"<<hn;
       for(int j = 1; j<hn+1; j++)
       {
        qh_data[FLD_HSDB_STINDEX] = qv_pkeys_lst.at(i);
        qh_data[FLD_HSDB_NAME] = QString().setNum(j);
        qh_data[FLD_HSDB_SPC] = sqrs[rand()%4];
        qh_data[FLD_HSDB_FACILITIES] = (int) 0xFFFF;
        qh_data[FLD_HSDB_TARIFF] = (double) (150.0 + (rand()%200)-100.0);
        int rnd = qrand()%100;
        int type = 0;
        if((70 < rnd) && (rnd <= 80)) type = 1;
        if(80<rnd) type = 2;
        qh_data[FLD_HSDB_TYPE] = type;
        qh_data[FLD_HSDB_COMMENTS] = RUSTR("комментарии :)");
        qv_re_key = mp_dbms->db_put(LAKDB_HOUSES,qh_data);
       }
   }
   qDebug()<<"houses db formed";
}

void DevelopArea::on_btn_test_clicked()
{
//        SleeQHash_Constrain constr;
//        quint64 key = 27ll;
//        quint64 key2 = 5ll;
//        double  square = 20;
//        QVariant qv_key = key;
//        QVariant qv_key2 = key2;
//        QVariant qv_sq = square;
//        //TODO: new constrain
//       // constr.append(qv_key,FLD_HSDB_STINDEX);
//        //constr.append(qv_key2,FLD_HSDB_STINDEX,CONSTR_OP_EQ,CONSTR_INTER_OR);
//        //constr.append(qv_sq, FLD_HSDB_SQUARE,CONSTR_OP_LESS,CONSTR_INTER_AND);
//        SLEE_HDB_REC_LST qh_data_lst;
//        QVariant qv_max = RUSTR("1");
//        mp_dbms->get_db(LAKDB_HOUSES)->findDataRange(FLD_HSDB_NAME,&qv_max,true,NULL,true, &qh_data_lst,&constr);
//        foreach(SLEE_HDB_REC qh_data, qh_data_lst)
//            qDebug()<<qh_data;
}

void DevelopArea::on_btn_form_apartments_clicked()
{
    QVariantList qv_pkey_lst;// = mp_dbms->get_db(LAKDB_HOUSES)->findDataRange(-1);
    int ap_num;
    SLEE_HDB_REC qh_data, qh_h_data;
    SLEE_HDB_REC_LST qh_house_data_lst;
    double total_space, live_space;
    QString qstr_temp;
    qv_pkey_lst = mp_dbms->get_db(LAKDB_HOUSES)->findDataRange(-1, NULL,true, NULL, false, &qh_house_data_lst);
    qv_pkey_lst.removeFirst();
    qh_house_data_lst.removeFirst();
    qDebug()<<"houses num in town"<<qv_pkey_lst.size();
    for(int i = 0; i<qv_pkey_lst.size(); i++)
    {
        ap_num = rand()%11 +3;
        qh_h_data = qh_house_data_lst.at(i);
        int house_type = qh_h_data[FLD_HSDB_TYPE].toInt();
        for(int j = 0; j < ap_num; j++)
        {
            qh_data[FLD_APDB_HSINDEX] = qv_pkey_lst[i];
            qh_data[FLD_APDB_NUMBER] = qstr_temp.setNum(j+1);
            total_space = rand()%31+10;
            qh_data[FLD_APDB_TSPC] = total_space;
            QVariantList qvl_lspaces, qvl_pdates;
            if( house_type == 0)
            {

                qh_data[FLD_APDB_RCOUNT] = rand()%4+1;
                live_space = total_space * 0.86;
                qh_data[FLD_APDB_COMMENTS] = RUSTR("многоквартирная квартирко");
                qvl_lspaces.append(QVariant(live_space));
                qvl_pdates.append(QVariant(QDate()));
            }
            if(house_type == 1)
            {
                qh_data[FLD_APDB_RCOUNT] = 1;
                live_space = total_space;
                qh_data[FLD_APDB_COMMENTS] = RUSTR("комната в общаге");
                qvl_lspaces.append(QVariant(live_space));
                qvl_pdates.append(QVariant(QDate()));
            }
            if(house_type == 2)
            {
                qh_data[FLD_APDB_RCOUNT] = rand()%8+2;
                int parts = qh_data[FLD_APDB_RCOUNT].toInt();
                live_space = total_space * 0.86;
                double space = live_space/parts;
                for(int z=0; z < parts; z++)
                {
                    qvl_lspaces.append(QVariant(space));
                    qvl_pdates.append(QVariant(QDate()));
                }
            }
            QVariantHash qvh_lspaces;
            QVariantHash qvh_pdates;
            for(int z = 0; z < qvl_lspaces.size(); z++)
            {
                QString qstr_key = HousingDBMS::gen_hash_str_key();
                qvh_lspaces[qstr_key] = qvl_lspaces.at(z);
                qvh_pdates[qstr_key] = qvl_pdates.at(z);
            }

            qh_data[FLD_APDB_LSPSHASH] = QVariant(qvh_lspaces);
            qh_data[FLD_APDB_PDATEHASH] = QVariant(qvh_pdates);

            qh_data[FLD_APDB_COMMENTS] = RUSTR("комментарии");
            if(!mp_dbms->get_db(LAKDB_APARTMENTS)->is_valid_data(qh_data))
            {
                qDebug()<<"error data validation";
                qDebug()<<"data size"<<qh_data.size();
                qDebug()<<"DATA: "<<qh_data;
                return;
            }
            mp_dbms->db_put(LAKDB_APARTMENTS,qh_data);
        }
        //if(!(i%30) && (i > 30))
            qDebug()<<"new apartments generated"<<i<<"of"<<qv_pkey_lst.size();
    }
}

void DevelopArea::on_btn_form_persons_db_clicked()
{

}

void DevelopArea::on_btn_form_tenants_clicked()
{
    QStringList qstrl_fams = read_families();
    QStringList qstrl_names = read_names();

    SLEE_HDB_REC qh_data;
    for(int i =0; i<1000; i++)
    {
        qh_data[FLD_TEN_FAM] = qstrl_fams.at(rand() % qstrl_fams.size());
        qh_data[FLD_TEN_NAME] = qstrl_names.at(rand() % qstrl_names.size());
        qh_data[FLD_TEN_PNAME] = qstrl_names.at(rand() % qstrl_names.size()) + RUSTR("вич");

        int year = 1930 + rand()%81;
        int mnth = rand()%12+1;
        int day = rand()%31+1;
         qh_data[FLD_TEN_DOB] =  QDate(year, mnth, day);

        qh_data[FLD_TEN_PASSNUM] = QString().sprintf("%.4d %.6d", rand()%9999, rand()%999999);
        year = 2000 + rand()%12;
        mnth = rand()%12+1;
        day = rand()%31+1;
        qh_data[FLD_TEN_PASSDATE] = QDate(year,mnth,day);
        qh_data[FLD_TEN_PASSDEP] = RUSTR("Лакинским ГОМ Собинского р-на Владимирской обл.");
        qh_data[FLD_TEN_COMM] = RUSTR("комментарии");
        qh_data[FLD_TEN_REGADR] = RUSTR("ЦФО Усть-Урюпинск д5 кв 45");
        mp_dbms->db_put(LAKDB_TENANTS,qh_data);
        qDebug()<<i<<"of 1000";
    }
}

void DevelopArea::on_btn_form_fam_memebers_clicked()
{
    QStringList qstrl_fams = read_families();
    QStringList qstrl_names = read_names();

    QStringList str_rel_lst = HousingDBMS::get_fam_relations();
    QVariantList qv_tkeys_lst = mp_dbms->get_db(LAKDB_TENANTS)->findDataRange(-1);
    SLEE_HDB_REC qh_data;
    int i = 0;
    foreach(QVariant qv_tkey, qv_tkeys_lst)
    {
        qh_data[FLD_FAM_TINDEX] = qv_tkey;

         int fam_size = rand()%6;
        QStringList str_fam_rel_lst;
        while(str_fam_rel_lst.size()<fam_size)
        {
            QString str_rel = str_rel_lst.at(rand()%str_rel_lst.size());
            if(str_fam_rel_lst.contains(str_rel)) continue;
            str_fam_rel_lst.append(str_rel);
        }

        for(int j =0; j<fam_size; j++)
        {
            qh_data[FLD_FAM_FAM] = qstrl_fams.at(rand() % qstrl_fams.size());
            qh_data[FLD_FAM_NAME] = qstrl_names.at(rand() % qstrl_names.size());
            qh_data[FLD_FAM_PNAME] = qstrl_names.at(rand() % qstrl_names.size()) + RUSTR("вич");

            int year = 1930 + rand()%81;
            int mnth = rand()%12+1;
            int day = rand()%31+1;
            qh_data[FLD_FAM_DOB] =  QDate(year, mnth, day);

            qh_data[FLD_FAM_RELATION] = str_fam_rel_lst.at(j);
            mp_dbms->db_put(LAKDB_FAMILIES,qh_data);
        }
        i++;
        qDebug()<<"new families i"<<i<<"total tenants"<<qv_tkeys_lst.size()<<"added fam size"<<fam_size;
    }
}

void DevelopArea::db_ready()
{
    ui->combo_tables->addItems(mp_dbms->get_db_names());
    mp_dbtable->load_db_list();
}


QStringList DevelopArea::read_families()
{
    QFile txt_file;
        txt_file.setFileName(mp_hs->str_home_path +"/txt_db/families-db.txt");
        if(!txt_file.open(QIODevice::ReadOnly))
        {
            qCritical()<<"Unable to open families txt data";
            return QStringList();
        }
        QTextStream txt_in(&txt_file);
        QString fam_str;
        QStringList fam_lst;
        while(!txt_in.atEnd())
        {
            txt_in>>fam_str;
            if(fam_str.size() < 2) continue;
            fam_str = fam_str.toUpper();
            if(fam_lst.contains(fam_str)) continue;
            fam_lst.append(fam_str);
        }
        txt_file.close();
        return fam_lst;
}

QStringList DevelopArea::read_names()
{
    QFile txt_file;
        txt_file.setFileName(mp_hs->str_home_path +"/txt_db/names-db.txt");
        if(!txt_file.open(QIODevice::ReadOnly))
        {
            qCritical()<<"Unable to open names txt data";
            return QStringList();
        }
        QTextStream txt_in(&txt_file);
        QString name_str;
        QStringList name_lst;
        while(!txt_in.atEnd())
        {
            txt_in>>name_str;
            if(name_str.size() < 2) continue;
            name_str = name_str.toUpper();
            if(name_lst.contains(name_str)) continue;
            name_lst.append(name_str);
        }
        txt_file.close();
        return name_lst;
}

void DevelopArea::on_btn_leases_clicked()
{
//    QVariantList qvl_ap_indices = mp_dbms->get_db(LAKDB_APARTMENTS)->findDataRange(-1);
//    qvl_ap_indices.removeFirst();
//    QVariantList qvl_ten_indices = mp_dbms->get_db(LAKDB_TENANTS)->findDataRange(-1);
//    qvl_ten_indices.removeFirst();
//    QVariantList qvl_dec_indices = mp_dbms->get_db(LAKDB_DECMASTERS)->findDataRange(-1);
//    qvl_dec_indices.removeFirst();

//    SLEE_HDB_REC qh_data;


////#define FLD_LS_DECLST       11//List of qv_key
////#define FLD_LS_DDATESLST 12//List decision dates list
////#define FLD_LS_DNUMLST    13//list of string


//SLEE_HDB_REC qh_ap_data;

//    for(int i = 0; i < 150; i++)
//    {
//        qh_data[FLD_LS_NUM] = i+1;
//        qh_data[FLD_LS_COMM] = RUSTR("Комментарии это тестовые данные");
//        qh_data[FLD_LS_LENDER_HEAD] = RUSTR("Главный председатель");
//        qh_data[FLD_LS_LENDER_HFIO] = RUSTR("Пупкин В.А.");
//        qh_data[FLD_LS_TINDEX] = qvl_ten_indices.at(qrand() % qvl_ten_indices.size());
//        qh_data[FLD_LS_AINDEX] = qvl_ap_indices.at(qrand() % qvl_ap_indices.size());
//        qh_ap_data = mp_dbms->get_data(LAKDB_APARTMENTS, qh_data[FLD_LS_AINDEX]);
//        int h_type = mp_dbms->get_house_type_str(qh_ap_data[FLD_APDB_HSINDEX]);
//        int rcount;
//        QString qsl_sp_indexes;
//        if(h_type < 2)
//        {
//            rcount  = qh_ap_data[FLD_APDB_RCOUNT].toInt() +1;
//            qsl_sp_indexes.append(QVariant(0));
//        }
//        if(h_type == 2)
//        {
//            rcount = qh_ap_data[FLD_APDB_RCOUNT].toInt();
//            int r = qrand() % (rcount-1) + 1;
//            qsl_sp_indexes.append(QVariant(r));
//        }
//        qh_data[FLD_LS_SPACELST] = qsl_sp_indexes;
//        int year = 2000 + rand()%15;
//        int mnth = rand()%12+1;
//        int day = rand()%31+1;
//        QDate qd_s = QDate(year,mnth, day);
//        qh_data[FLD_LS_SDATE] = qd_s;
//        qh_data[FLD_LS_REASON] = RUSTR("Действующий");
//        qh_data[FLD_LS_EDATE] = QDate(2100, 1, 1);
//        if(! (qrand() % 10))
//        {
//            QList<QDate> qdl_pdates;
//            QDate pdate = qd_s.addYears(qrand() % 11 +2);
//            qh_data[FLD_LS_EDATE] = pdate;
//            qh_data[FLD_LS_REASON] = RUSTR("Приватизация  ж.п.");
//            for(int i = 0; i<qsl_sp_indexes.size(); i++)
//                    qdl_pdates.append(pdate);
//          //  mp_dbms->privatize_lspace(qh_data.value(FLD_LS_AINDEX),qsl_sp_indexes,qdl_pdates);
//        }
//        QVariantList qvl_decs;
//        QVariantList qvl_ddates;
//        QVariantList qvl_dnums;
//        int dec_count = qrand() % qvl_dec_indices.size() + 1;
//        for(int j = 0; j<dec_count; j++ )
//        {
//            QVariant qv_dindex = qvl_dec_indices.at(j);
//            QDate qd_ddate = qd_s.addMonths(-1);
//            int num = qrand() % 1000 + 1;
//            qvl_decs.append(qv_dindex);
//            qvl_ddates.append(QVariant(qd_ddate));
//            qvl_dnums.append(QVariant(num));
//        }
//        qh_data[FLD_LS_DECLST] = qvl_decs;
//        qh_data[FLD_LS_DDATESLST] = qvl_ddates;
//        qh_data[FLD_LS_DNUMLST] = qvl_dnums;
//        mp_dbms->db_put(LAKDB_LEASES, qh_data);
//        qDebug()<<"Lease added "<<i+1<<"/"<<3000;
//    }


}

void DevelopArea::on_btn_fake_payments_clicked()
{
//    QVariantList qvl_ap_indices = mp_dbms->get_db(LAKDB_APARTMENTS)->findDataRange(-1);
//    qvl_ap_indices.removeFirst();
//    QList<int> ql_years;
//    ql_years<<2005<<2006<<2007<<2008<<2009<<2010<<2011<<2012;
//    foreach(int year, ql_years)
//    {
//        qDebug()<<"*****************************"<<year<<"**********************************";
//        for(int i = 1; i<= 12; i++)
//        {
//            qDebug()<<"\t********************"<<i<<"************************";
//            QDate qd(year,i, 15);
//            int jj = 0;
//            int size = qvl_ap_indices.size();
//            foreach(QVariant qv_ap_index, qvl_ap_indices)
//            {
//                jj++;
//                if((qrand()%100) < 80) continue;
//                qDebug()<<"-----------inprocess: "<<jj<<"/"<<size-1;
//                SLEE_HDB_REC qh_ap = mp_dbms->get_data(LAKDB_APARTMENTS, qv_ap_index);
//                SLEE_HDB_REC qh_pay;
//                qh_pay[FLD_PDB_AINDEX] = qv_ap_index;
//                qh_pay[FLD_PDB_TARGETDATE] = qd;
//                qh_pay[FLD_PDB_AMMOUNT] = (double)3000.35 + qrand() %1000-500;
//                qh_pay[FLD_PDB_DATE] = qd.addDays(qrand() %150 -20);
//                QVariantList qvl = qh_ap.value(FLD_APDB_LSPCLST).toList();
//                QVariantList qvl_sid;
//                for(int i=0; i<qvl.size(); i++) qvl_sid.append(QVariant(i));
//                qh_pay[FLD_PDB_SPIDLST] = qvl_sid;
//                mp_dbms->db_put(LAKDB_PAYMENTS, qh_pay);
//            }

//        }
//    }

}
